package com.fandou.airobot.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.Utils;
import com.fandou.airobot.database.Alarm;
import com.fandou.airobot.database.AlarmDatabase;

import java.util.List;

/**
 * @author Jm
 * @date 2020/7/01 10:45
 * @description 设置现有的闹钟services
 */
public final class LoadAlarmsService extends IntentService {

    private static final String TAG = LoadAlarmsService.class.getSimpleName();

    public static final String ACTION_COMPLETE = TAG + ".ACTION_COMPLETE";

    public static final String ALARMS_EXTRA = "alarms_extra";

    public LoadAlarmsService() {
        this(TAG);
    }

    public LoadAlarmsService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        final List<Alarm> alarms = AlarmDatabase.getInstance().alarmDao().getAllAlarms();
        AlarmReceiver.setReminderAlarms(Utils.getApp(), alarms);

        for (int i = 0; i < alarms.size(); i++) {

            Alarm alarm = alarms.get(i);
            //如果该闹钟不是重复闹钟，并且已经过期，则关闭这个闹钟
            if (!alarm.getRepeat() && alarm.getTime() < TimeUtils.getNowMills()) {
                alarm.setEnable(false);
                AlarmDatabase.getInstance().alarmDao().updateAlarm(alarm);
            }
        }
    }

    /**
     * 启动一个 重新设置闹钟的intentServices
     * 一般用于程序入口，进行重新设置闹钟
     *
     * @param context context
     */
    public static void launchLoadAlarmsService(Context context) {
        final Intent launchLoadAlarmsServiceIntent = new Intent(context, LoadAlarmsService.class);
        context.startService(launchLoadAlarmsServiceIntent);
    }

}
